﻿using System;
using System.Collections.Generic;
using System.Linq;
using LinqToTwitter;
using Microsoft.SystemCenter.Orchestrator.Integration;
using searchFilter = System.Linq.Expressions.Expression<System.Func<LinqToTwitter.Status, bool>>;

namespace SocialMediaIntegrationPack
{
    [Activity("Twitter Monitor")]
    [ActivityMonitor(Interval = 60)] // Interval in seconds
    public class MonitorTweetAct : GetTweetAct
    {
        private readonly HashSet<string> statusIdCache;
        private readonly DateTime startTime;

        public MonitorTweetAct()
        {
            statusIdCache = new HashSet<string>();
            startTime = DateTime.UtcNow;
        }

        protected override IEnumerable<searchFilter> GetAdditionalFilters()
        {
            var filters = base.GetAdditionalFilters() ?? new List<searchFilter>();
            return filters.Concat(new List<searchFilter> { 
                            tweet => !statusIdCache.Contains(tweet.StatusID)
                            && tweet.CreatedAt.CompareTo(startTime) >= 0 });
        }

        protected override void AfterSearchComplete(IQueryable<Status> result)
        {
            result.ToList().ForEach(tweet => statusIdCache.Add(tweet.StatusID));
        }
    }
}
